<template>
  <el-card class="directory-page">
    <div class="header">
      <div class="search">
        <el-form
          :model="formInline"
          class="demo-form-inline"
          label-width="70px"
        >
          <el-row :gutter="10">
            <el-col :span="8">
              <el-form-item label="目录名称">
                <el-input v-model="formInline.directoryName"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="状态">
                <el-select v-model="formInline.status" placeholder="请选择">
                  <el-option label="启用" :value="1"> </el-option>
                  <el-option label="禁用" :value="0"> </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-button @click="formInline = {}">清空</el-button>
              <el-button type="primary" @click="onSubmit">搜索</el-button>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <div class="add">
         <el-button v-if="subjects.id && subjects.name" type="text" icon="el-icon-back" @click="$router.back()">返回学科</el-button>
        <el-button type="success" class="el-icon-edit" @click="add"
          >新增目录</el-button
        >
      </div>
    </div>

    <el-alert
      :title="`共${counts}条记录`"
      type="info"
      show-icon
      :closable="false"
    >
    </el-alert>
    <el-table
      :header-cell-style="{ background: '#FAFAFA' }"
      :data="subjectData"
      style="width: 100%; margin-top: 20px"
    >
      <el-table-column prop="id" label="序号" width="80"> </el-table-column>
      <el-table-column prop="subjectName" label="所属学科"> </el-table-column>
      <el-table-column prop="directoryName" label="目录名称"> </el-table-column>
      <el-table-column prop="username" label="创建者"> </el-table-column>
      <el-table-column prop="addDate" label="创建日期" :formatter="dateFormat">
      </el-table-column>
      <el-table-column prop="totals" label="面试题数量"> </el-table-column>
      <el-table-column prop="state" label="状态" :formatter="stateFormat">
      </el-table-column>

      <el-table-column label="操作" align="center" width="220">
        <template #default="scope">
          <el-button type="text" @click="editState(scope.row)">{{
            scope.row.state === 1 ? "禁用" : "启用"
          }}</el-button>
          <el-button
            type="text"
            :disabled="scope.row.state === 1"
            @click="edit(scope.row)"
            >修改</el-button
          >
          <el-button
            type="text"
            :disabled="scope.row.state === 1"
            @click="del(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination
        background
        layout="prev, pager, next,sizes,jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="params.page"
        :page-sizes="[10, 20, 30, 50]"
        :total="counts"
      >
      </el-pagination>
    </div>
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="30%"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="directoryForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="所属学科" prop="subjectID" style="width: 100%">
          <el-select v-model="directoryForm.subjectID" placeholder="请选择">
            <el-option
              v-for="item in subjectOption"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="目录名称" prop="directoryName">
          <el-input v-model="directoryForm.directoryName"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </span>
    </el-dialog>
  </el-card>
</template>

<script>
import { list, changeState, add, update, remove } from '@/api/hmmm/directorys'
import { simpleSubject } from '@/api/hmmm/subjects'

export default {
  data () {
    return {
      formInline: {
        directoryName: '',
        status: null
      },
      params: {

        page: 1,
        pagesize: 10,
        directoryName: ''

      },
      title: '',
      directoryForm: {
        subjectID: '',
        directoryName: ''
      },
      subjectData: [],
      counts: null,

      dialogVisible: false,

      subjectOption: [],
      rules: {
        subjectID: [
          { required: true, message: '所属学科不能为空', trigger: 'blur' }
        ],
        directoryName: [
          { required: true, message: '目录名称不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.list()
    this.simpleSubject()
  },
  computed: {
    subjects () {
      return this.$route.query || null
    }
  },

  // 侦听地址栏数据
  watch: {
    '$route.query' () {
      this.getDirectList()
    }
  },
  methods: {
    // 切换状态
    async editState (row) {
      try {
        await changeState({
          id: row.id,
          state: row.state === 1 ? 0 : 1
        })
        this.$message.success('操作成功')
        row.state = row.state === 1 ? 0 : 1
      } catch (e) {
        this.$message.error('请求错误!')
      }
    },
    onSubmit () {
      this.params.directoryName = this.formInline.directoryName
      this.params.state = this.formInline.status

      this.list()
    },
    async list () {
      this.params.subjectID = this.subjects.id || null
      const { data } = await list(this.params)

      this.subjectData = data.items
      this.counts = data.counts
    },
    dateFormat (row) {
      return this.$dayjs(row.addDate).format('YYYY-MM-DD')
    },
    stateFormat (row) {
      if (row.state === 1) {
        return '已启用'
      } else if (row.state === 0) {
        return '已禁用'
      }
    },
    async simpleSubject () {
      const { data } = await simpleSubject()

      this.subjectOption = data
    },
    handleSizeChange (val) {
      this.params.pagesize = val
      this.list()
    },
    handleCurrentChange (current) {
      this.params.page = current
      this.list()
    },
    async add () {
      this.title = '新增目录'
      this.dialogVisible = true
      await this.$refs.formRef.resetField()
    },
    async edit (row) {
      this.title = '修改目录'
      this.dialogVisible = true

      this.directoryForm.id = row.id
      this.directoryForm.subjectID = row.subjectID
      this.directoryForm.directoryName = row.directoryName
    },

    async save () {
      try {
        if (this.title === '新增目录') {
          await this.$refs.formRef.validate()
          const res = await add(this.directoryForm)

          if (res.status === 200) {
            this.$message.success('添加成功')
          } else {
            this.$message.error('添加失败')
          }
        } else {
          const res = await update(this.directoryForm)
          if (res.status === 200) {
            this.$message.success('修改成功')
          } else {
            this.$message.error('修改失败')
          }
        }
        this.dialogVisible = false
        this.list()
      } catch (err) {
        this.$message.error(err.response.data)
      }
    },
    async del (row) {
      await this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      await remove(row)

      this.$message({
        type: 'success',
        message: '删除成功!'
      })
      this.list()
    }
  }
}
</script>

<style scoped lang="scss">
.directory-page {
  margin: 20px 20px;
  .header {
    display: flex;
    justify-content: space-between;
  }
  .pagination {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
  }
  .el-dialog {
    .dialog-footer {
      display: block;
      text-align: center;
    }
  }
}
</style>
